import { createRouter, createWebHistory } from 'vue-router';
import type { RouteRecordRaw } from 'vue-router';
import { useUserStore } from '@/stores/user';
import { useRouterStore } from '@/stores/routerStore';
import { useRoleMenuStore } from '@/stores/roleMenuStore';
import { jwtDecode } from 'jwt-decode';

const routes: RouteRecordRaw[] = [
    {
        path: '/',
        redirect: '/overview',
    },
    {
        path: '/login',
        component: () => import('@/components/Login.vue'),
        meta: { requiresAuth: false, icon: "" }
    },
    {
        path: '/overview',
        component: () => import('@/views/AboutView.vue'),
        meta: { requiresAuth: true, icon: "Calendar", title: "概览" }
    },   
];

const router = createRouter({
    history: createWebHistory(),
    routes
});
const handleNavigationGuard = () => {
    router.beforeEach(async (to, from) => {
        const userStore = useUserStore();
        const token = localStorage.getItem('token');
        const roleMenuStore = useRoleMenuStore();
        const routeStore = useRouterStore();

        if (to.path === '/login') {
            return true;
        }
        if (to.meta.requiresAuth && (!token ||!userStore.isLoggedIn)) {
            return '/login';
        }
        if (!routeStore.hasFetchedRoutes) {
            const loginInfo = jwtDecode(token as string) as { username: string, role: string };
            const data = await roleMenuStore.fetchRoleMenus(loginInfo.role);
            const modules = import.meta.glob(['../views/**/*.vue', '../components/**/*.vue']);
            data?.forEach((item) => {
                let componentPath;
                const componentName = item.component.endsWith('.vue') ? item.component : `${item.component}.vue`;
                if (componentName.includes('/views/')) {
                    componentPath = `../${componentName}`;
                } else {
                    componentPath = `../${componentName}`;
                }
                const route = {
                    path: item.path,
                    component: modules[componentPath] || (() => import('@/components/NotFound.vue')),
                    meta: { requiresAuth: true, title: item.name, icon: item.icon }
                };
                router.addRoute(route);
            });
           
            routeStore.hasFetchedRoutes = true;
            return router.push(to.path);
        }
        return true;
    });
};

handleNavigationGuard();

export default router;